<?php
/**
 * @author hjj
 * 义乌易镭供应商订单SDK
 */

namespace App\Service\VendorClient\ShopywyleiApi;

use App\Service\Code\Normal;
use App\Service\BaseService;
use Service\AppService\IdService;
use App\Service\TaskServer\TaskWorker;
use App\Model\PssModel\ServiceConfig;

class ShopYwyleiApiClient extends BaseService
{
    //供应商编号
    const SUPPLIER_CODE = 'shopywylei';
    private $config = [];
    public function __construct($apiBody = [])
    {
        $this->config = $apiBody;
    }

    /**
     * 创建订单
     * @param array $params
     * @return mixed
     */
    public function createOrder( $param = [] )
    {
        $orderInfo   = $param['supplierOrder'];
        $goodsList   = $param['orderGoods'];
        $order       = $param['order'];
        $binfo       = $param['binfo'];
        $companyInfo = $param['companyInfo'];
        $order_sn    = $orderInfo['supplier_dsn'];
        //支付流水号
        $pay_sn = $order['paySerial'] ?? $orderInfo['pay_sn'];
        //订单时间
        $order_time = $orderInfo['cd'] ? date('Y-m-d H:i:s', $orderInfo['cd']) : date('Y-m-d H:i:s', time());
        //支付时间
        $pay_time = isset($order['payTime']) && !empty($order['payTime']) ? date('Y-m-d H:i:s', $order['payTime']) : date('Y-m-d H:i:s', time());
        //运费分摊
        $deliver_money = $orderInfo['deliver_money'] ?? 0.00;
        //下单支付的时候支付信息
        $apply_extends = @json_decode($orderInfo['apply_extends'], true);
        //判断支付方式是否存在
        $payCommanyName = $apply_extends['payCommanyName']??'';
        $payCommanyName = $order['payCommanyName'] ?? $payCommanyName ;
        $payWayInfo = ServiceConfig::instance()->getConfigByEventsValue(self::SUPPLIER_CODE, ServiceConfig::TYPE_PAY, $payCommanyName);
        if (empty($payWayInfo)) {
            return Normal::returnCode(Normal::FAIL, "支付公司名称：【{$payCommanyName}】未映射，请联系管理员处理");
        }
        //获取下单商品信息
        $palceOrderGoods = [];
        foreach ($goodsList as $key => $item) {
            //卖价
            $price = $item['price'];
            //商品购买数量
            $quantity = $item['quantity'];//2
            //下单商品组
            $goodsInfo         = [
                'itemNo'       => $item['supplier_skucode'],//商品编码
                'itemQuantity' => (int)$quantity,//订购数量
                'itemPrice'    => (float)$price,//单价 包含税费
            ];
            $palceOrderGoods[] = $goodsInfo;
        }
        $requestParam = [
            'OrderNo'         => $order_sn,//订单编号 / 海关申报订单号
            'OrderOutNo'      => $order_sn,//外部订单编号
            'FeeAmount'       => (float)$deliver_money,//不含税运费
            'CreateTime'      => $order_time,//订单创建时间
            'ShopName'        => $this->config['shopname'],//第三方平台名称,参考数据字典，自营订单可以不填
            'PayAmount'       => (float)$orderInfo['real_total_money'],//订单支付金额
            'PayCompanyName'  => $payWayInfo,//支付企业
            'PayOrderNo'      => $order['paySerial'] ?? $apply_extends['paySerial'],//支付单号
            'PayTime'         => $pay_time,//支付时间
            'PurcName'        => $orderInfo['buyer_realname'],//订购人姓名
            'PurcPaperNumber' => $orderInfo['buyer_idcard'],//订购人身份证号
            'Consignee'       => $orderInfo['receive_name'],//收货人姓名
            'ConsigneeTel'    => $orderInfo['recveive_phone'],//收货人手机号
            'Province'        => $orderInfo['province'],//省份
            'City'            => $orderInfo['city'],//城市
            'Area'            => $orderInfo['district'],//城市
            'Address'         => $orderInfo['receive_address'],//详细地址
            'OrderItems'      => $palceOrderGoods,//商品明细
        ];
        $data = [
            'method' => 'createOrder',
            'data'   => $requestParam,
        ];
        return $this->execute($data);
    }

    /**
     * 商品列表
     */
    public function queryGoodsList($param=[])
    {
        $requestParam = [
            'method'    => 'queryGoods',
            'data'   => [
                'page'=> $param['page']??1,
                'pagesize'=>$param['limit']??50,
            ]
        ];
        $response=$this->execute($requestParam);
        if ($response['code']!=Normal::SUC){
            return $response;
        }
        $skuNos= array_column($response['data']['data'],'goodsItem');
        //库存
        $stockList=$this->queryStockSynchro($skuNos);
        //组装数据
        foreach ($response['data']['data'] as &$v){
            $v['stock_info']=$stockList[$v['goodsItem']]??0;
            unset($v);
        }

        return $response;
    }

    /**
     * 获取商品库存
     */
    public function queryStockSynchro($skuNos)
    {
        //创建订单数据
        $data = [
            "goodsItems" => $skuNos,
        ];
        $requestParam = [
            'method'    => 'queryStock',
            'data'      => $data,
        ];
        $stockListRes=$this->execute($requestParam);
        if ($stockListRes['code']!=Normal::SUC){
            return Normal::returnCode(Normal::SUC,'获取库存成功',[]);
        }
        return Normal::returnCode(Normal::SUC,'获取库存成功',array_column($stockListRes['data']['stocks'], null, 'goodsItem'));
    }

    /**
     * 签名
     * @param $data
     * @return string
     */
    public function sign($data)
    {
        $stringA = json_encode($data);
        $stringB = $this->config['appkey'] . $stringA . $this->config['appkey'];
        $stringC = md5($stringB);
        return strtoupper($stringC);
    }

    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute( $param = [] )
    {
        $method = $param['method'];
        $data   = $param['data'];
        if (!isset($this->config[$method])) {
            return Normal::returnCode(Normal::FAIL, "请求路由未设置");
        }
        if (empty($param['data'])) {
            return Normal::returnCode(Normal::FAIL, "数据不能为空");
        }
        $url = $this->config['baseurl'] . $this->config[$method];
        if (empty($url)) {
            return Normal::returnCode(Normal::FAIL, "接口地址不能为空");
        }
        $commonData = [
            'partnerid' => $this->config['partnerid'],
        ];
        $pushData   = array_merge($commonData, $param['data']);
        $sign       = $this->sign($pushData);
        $parameter  = [
            [
                'tag'    => self::SUPPLIER_CODE . '_' . $method,
                'uid'    => IdService::instance()->getOtherID(),
                'url'    => $url,
                'data'   => $pushData,
                'method' => 'post',
                'format' => 'json',
                'header' => [
                    "Content-Type: application/json",
                    "sign: {$sign}",
                ],
            ],
        ];
        if( in_array($method,['queryGoods','queryStock']) ) {
            $resTask = TaskWorker::instance()->addTask($parameter,'handleDiableTask');
        } else {
            $resTask = TaskWorker::instance()->addTask($parameter);
        }
        $resTask    = current($resTask);
        $result     = @json_decode($resTask['response']['result'], true);
        if (isset($result['success']) && $result['success'] == 'True') {
            return Normal::returnCode(Normal::SUC, "操作成功", $result);
        } else {
            $msg = $result['message'] ?? '请求失败';
            return Normal::returnCode(Normal::FAIL, $msg);
        }
    }

}
